from collections import OrderedDict
from goods.models import GoodsChannel


def get_categories():
    """
        商品频道及分类菜单
        使用有序字典保存类别的顺序
        categories = {
            1: { # 组1
                'channels': [{'id':, 'name':, 'url':},{}, {}...],
                'sub_cats': [{'id':, 'name':, 'sub_cats':[{},{}]}, {}, {}, ..]
            },
            2: { # 组2

            }
        }
        """
    # 大字典,有序字典
    categories = OrderedDict()
    # 获取频道里（就是那个框）的所有对象（对象包括组号，组内排序）
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    for channel in channels:
        # 判断频道组号是否存在字典中
        if channel.group_id not in categories:
            categories[channel.group_id] = {
                'channels': [],  # 存放一级分类
                'sub_cats': []  # 存放二级分类
            }

        categories[channel.group_id]['channels'].append({
            'id': channel.category_id,
            'name': channel.category.name,
            'url': channel.url
        })
        # 添加2级分类
        for sub2 in channel.category.goodscategory_set.all():
            # 添加三级分类
            sub2.sub_cats = []
            for sub3 in sub2.goodscategory_set.all():
                sub2.sub_cats.append(sub3)
            categories[channel.group_id]['sub_cats'].append(sub2)

    return categories
